package com.zhuoya.healthcard;

import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.util.Log;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zhuoya.healthcard.contants.Contants;
import com.zhuoya.healthcard.entity.FaceStatusEnum;
import com.zhuoya.healthcard.entity.OrderInfo;
import com.zhuoya.healthcard.util.HttpUtil;
import com.zhuoya.healthcard.util.SoundPoolHelper;
import com.zhuoya.healthcard.util.ToastUtil;
import com.ldoublem.loadingviewlib.view.LVCircularZoom;
import com.tx.printlib.UsbPrinter;
import com.zkteco.android.biometric.core.device.BiometricFactory;
import com.zkteco.android.biometric.core.device.ParameterHelper;
import com.zkteco.android.biometric.core.device.TransportType;
import com.zkteco.android.biometric.core.utils.LogHelper;
import com.zkteco.android.biometric.module.idcard.IDCardReader;
import com.zkteco.android.biometric.module.idcard.IDCardReaderFactory;
import com.zkteco.android.biometric.module.idcard.exception.IDCardReaderException;
import com.zkteco.android.biometric.module.idcard.meta.IDCardInfo;


import java.io.File;
import java.io.FileOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class ScanCardActivity extends BaseActity {
    private static final String LOG_TAG;
    private LVCircularZoom mLoading;
    private UsbPrinter mUsbPrinter;

    private static final int VID = 1024;    //IDR VID
    private static final int PID = 50010;     //IDR PID
    private IDCardReader idCardReader = null;
    private TextView textView = null;
    private boolean bopen = false;
    private boolean bStoped = false;
    private int mReadCount = 0;
    private CountDownLatch countdownLatch = new CountDownLatch(1);

    private Context mContext = null;
    private UsbManager musbManager = null;
    private final String ACTION_USB_PERMISSION = "com.example.scarx.idcardreader.USB_PERMISSION";

    private BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (ACTION_USB_PERMISSION.equals(action)) {
                synchronized (this) {
                    UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                    if (intent.getBooleanExtra(UsbManager.EXTRA_PERMISSION_GRANTED, false)) {
                    } else {
                        Toast.makeText(mContext, "USB未授权", Toast.LENGTH_SHORT).show();
                        //mTxtReport.setText("USB未授权");
                    }
                }
            }
        }
    };
    private int pageStatus;
    protected SoundPoolHelper soundPoolHelper;

    static {
        LOG_TAG = DistingushCardActivity.class.getSimpleName();
    }

    private void RequestDevicePermission() {
        musbManager = (UsbManager) this.getSystemService(Context.USB_SERVICE);
        IntentFilter filter = new IntentFilter();
        filter.addAction(ACTION_USB_PERMISSION);
        filter.addAction(UsbManager.ACTION_USB_ACCESSORY_ATTACHED);
        mContext.registerReceiver(mUsbReceiver, filter);

        for (UsbDevice device : musbManager.getDeviceList().values()) {
            if (device.getVendorId() == VID && device.getProductId() == PID) {
                Intent intent = new Intent(ACTION_USB_PERMISSION);
                PendingIntent pendingIntent = PendingIntent.getBroadcast(mContext, 0, intent, 0);
                musbManager.requestPermission(device, pendingIntent);
            }
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    private UsbDevice getCorrectDevice() {
        final UsbManager usbMgr = (UsbManager) getSystemService(Context.USB_SERVICE);
        final Map<String, UsbDevice> devMap = usbMgr.getDeviceList();
        for (String name : devMap.keySet()) {
            Log.v(LOG_TAG, "check device: " + name);
            if (UsbPrinter.checkPrinter(devMap.get(name))) {
                final UsbDevice usbDevice = devMap.get(name);
                final String productName = usbDevice.getProductName();
                if (productName != null && " TX PRINTER ".equals(productName)) {
                    return usbDevice;
                }
                continue;
            }
        }
        return null;
    }

    private void startIDCardReader() {
        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        this.idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);
    }

    public static void writeLogToFile(String log) {
        try {
            File dirFile = new File("/sdcard/zkteco/");  //目录转化成文件夹
            if (!dirFile.exists()) {              //如果不存在，那就建立这个文件夹
                dirFile.mkdirs();
            }
            String path = "/sdcard/zkteco/idrlog.txt";
            File file = new File(path);
            if (!file.exists()) {
                File dir = new File(file.getParent());
                dir.mkdirs();
                file.createNewFile();
            }
            FileOutputStream outStream = new FileOutputStream(file, true);
            log += "\r\n";
            outStream.write(log.getBytes());
            outStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void OnBnBegin() {
        try {
            if (this.bopen) {
                return;
            }
            this.RequestDevicePermission();
            this.idCardReader.open(0);
            this.bStoped = false;
            this.mReadCount = 0;
            writeLogToFile("连接设备成功");
            this.bopen = true;
            new Thread(new Runnable() {
                @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
                @Override
                public void run() {
                    while (!bStoped) {
                        try {
                            Thread.sleep(500);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        boolean bSamStatus = false;
                        try {
                            if (idCardReader != null) {
                                bSamStatus = idCardReader.getStatus(0);
                            }
                        } catch (IDCardReaderException e) {
                            e.printStackTrace();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

                        if (!bSamStatus) {
                            try {
                                idCardReader.reset(0);
                            } catch (IDCardReaderException e) {
                                e.printStackTrace();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                        final IDCardInfo idCardInfo = new IDCardInfo();
                        boolean ret = false;
                        try {
                            idCardReader.findCard(0);
                            idCardReader.selectCard(0);
                        } catch (IDCardReaderException e) {
                            LogHelper.e("errcode:" + e.getErrorCode() + ",internalerrorcode:" + e.getInternalErrorCode());
                            //continue;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        try {
                            Thread.sleep(50);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        try {
                            ret = idCardReader.readCard(0, 0, idCardInfo);
                        } catch (IDCardReaderException e) {
                            writeLogToFile("读卡失败，错误信息：" + e.getMessage());
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                        if (ret) { // 读卡成功
                            runOnUiThread(new Runnable() {
                                public void run() {
                                    // 加载动画
                                    ScanCardActivity.this.mLoading.setVisibility(View.VISIBLE);
                                    ScanCardActivity.this.mLoading.startAnim();
                                }
                            });
                            try {
                                if (ScanCardActivity.this.pageStatus == 1) { // 打印登记单
                                    JSONObject param = new JSONObject();
                                    param.put("idCard", idCardInfo.getId());
                                    param.put("name", idCardInfo.getName());
                                    param.put("hospitalId", Contants.HOSPITALID);
                                    // 查询个人预约信息
                                    String result = HttpUtil.submitPostData(Contants.uri + "order/findByIdcard", param, "utf-8");
                                    final JSONObject resJSON = JSONObject.parseObject(result);
                                    final int code = resJSON.getInteger("code");
                                    final String msg = resJSON.getString("msg");
                                    runOnUiThread(new Runnable() {
                                        @Override
                                        public void run() {
                                            if (code == 0) {
                                                JSONObject orderJSON = resJSON.getJSONObject("order");
                                                OrderInfo orderInfo = new OrderInfo();
                                                orderInfo.setId(orderJSON.getInteger("id"));
                                                orderInfo.setPhone(orderJSON.getString("phone"));
                                                orderInfo.setWork(orderJSON.getString("sshy"));
                                                orderInfo.setName(idCardInfo.getName());
                                                orderInfo.setIdcard(idCardInfo.getId());
                                                orderInfo.setPhoto(idCardInfo.getPhoto());
                                                orderInfo.setNation(idCardInfo.getNation());
                                                orderInfo.setValidityTime(idCardInfo.getValidityTime());
                                                orderInfo.setWorkName(orderJSON.getString("workName"));
                                                orderInfo.setIsExpress("2".equals(orderJSON.getString("express")) ? "是" : "否");

                                                // 展示个人信息
                                                Intent intent = new Intent(ScanCardActivity.this, PersonInfoActivity.class);
                                                Bundle localBundle = new Bundle();
                                                localBundle.putSerializable("info", orderInfo);
                                                intent.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                                intent.putExtras(localBundle);
                                                ScanCardActivity.this.startActivity(intent);
                                                ScanCardActivity.this.finish();
                                            } else if (code == 1) {
                                                Intent inten = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                                inten.putExtra("code", 1);
                                                inten.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                                inten.putExtra("errorInfo", "预约医院非本院，暂无法办理");
                                                ScanCardActivity.this.startActivity(inten);
                                                ScanCardActivity.this.finish();
                                            } else if (code == 2) {
                                                Intent inten = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                                inten.putExtra("code", 2);
                                                inten.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                                ScanCardActivity.this.startActivity(inten);
                                                ScanCardActivity.this.finish();
                                            } else if (code == 3) {
                                                Intent inten = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                                inten.putExtra("code", 3);
                                                inten.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                                inten.putExtra("errorInfo", "暂无预约信息");
                                                ScanCardActivity.this.startActivity(inten);
                                                ScanCardActivity.this.finish();
                                            } else if (code == 505) {
                                                Intent inten = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                                inten.putExtra("code", 4);
                                                inten.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                                ScanCardActivity.this.startActivity(inten);
                                                ScanCardActivity.this.finish();
                                            } else {
                                                ScanCardActivity.this.mLoading.setVisibility(View.INVISIBLE);
                                                ToastUtil.show(ScanCardActivity.this, msg);
                                                ScanCardActivity.this.startActivity(new Intent(ScanCardActivity.this, MainActivity.class));
                                                ScanCardActivity.this.finish();
                                            }
                                        }
                                    });

                                } else if (ScanCardActivity.this.pageStatus == 2) { // 叫号小票
                                    JSONObject param = new JSONObject();
                                    param.put("idCard", idCardInfo.getId());
                                    param.put("name", idCardInfo.getName());
                                    param.put("hospitalId", Contants.HOSPITALID);
                                    JSONObject resJSON = JSON.parseObject(HttpUtil.submitPostData(Contants.uri + "callNumber/collecTickets", param, "utf-8"));
                                    int code = resJSON.getInteger("code").intValue();
                                    String msg = resJSON.getString("msg");
                                    if (code == 0) {
                                        String waitCount = resJSON.getString("waitCount");
                                        JSONObject callNumberInfoJSON = resJSON.getJSONObject("callNumberInfo");
                                        String number = callNumberInfoJSON.getString("number");
                                        String name = callNumberInfoJSON.getString("name");
                                        String printInfo = print(name, number, waitCount);
                                        if ("8018H".equals(printInfo)) {
                                            runOnUiThread(new Runnable() {
                                                public void run() {
                                                    ScanCardActivity.this.startActivity(new Intent(ScanCardActivity.this, PrintSuccessActivity.class));
                                                    ScanCardActivity.this.finish();
                                                }
                                            });
                                        } else {
                                            JSONObject errParam = new JSONObject();
                                            errParam.put("hospitalId", Integer.valueOf(Contants.HOSPITALID));
                                            errParam.put("number", number);
                                            errParam.put("name", name);
                                            errParam.put("idCard", idCardInfo.getId());
                                            HttpUtil.submitPostData(Contants.uri + "callNumber/removeNumber", errParam, "utf-8");
                                            if ("8028H".equals(printInfo)) {
                                                runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        Intent intent = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                                        intent.putExtra("errorInfo", "打印机缺纸");
                                                        intent.putExtra("code", 3);
                                                        intent.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                                        ScanCardActivity.this.startActivity(intent);
                                                        ScanCardActivity.this.finish();
                                                    }
                                                });
                                            } else {
                                                runOnUiThread(new Runnable() {
                                                    public void run() {
                                                        Intent intent = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                                        intent.putExtra("errorInfo", "打印机错误");
                                                        intent.putExtra("code", 3);
                                                        intent.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                                        ScanCardActivity.this.startActivity(intent);
                                                        ScanCardActivity.this.finish();
                                                    }
                                                });
                                            }
                                        }
                                    } else if (code == 505) {
                                        runOnUiThread(new Runnable() {
                                            public void run() {
                                                Intent localIntent = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                                localIntent.putExtra("errorInfo", "网络异常");
                                                localIntent.putExtra("code", 4);
                                                localIntent.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                                ScanCardActivity.this.startActivity(localIntent);
                                                ScanCardActivity.this.finish();
                                            }
                                        });
                                    } else {
                                        ScanCardActivity.this.runOnUiThread(new Runnable() {
                                            public void run() {
                                                Intent localIntent = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                                localIntent.putExtra("errorInfo", "服务器异常");
                                                localIntent.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                                ScanCardActivity.this.startActivity(localIntent);
                                                ScanCardActivity.this.finish();
                                            }
                                        });
                                    }
                                } else if (ScanCardActivity.this.pageStatus == 3) { // 选择寄送
                                    JSONObject param = new JSONObject();
                                    param.put("idCard", idCardInfo.getId());
                                    final JSONObject resJSON = JSON.parseObject(HttpUtil.submitPostData(Contants.uri + "order/selectSendQualification", param, "utf-8"));
                                    final int code = resJSON.getInteger("code");
                                    final String msg = resJSON.getString("msg");
                                    if (code == 0) {
                                        runOnUiThread(new Runnable() {
                                            @Override
                                            public void run() {
                                                int registrationId = resJSON.getInteger("registrationId");
                                                String expressMoney = resJSON.getString("expressMoney");
                                                Intent localIntent = new Intent(ScanCardActivity.this, DeliveryInfoActivity.class);
                                                localIntent.putExtra("name", idCardInfo.getName());
                                                localIntent.putExtra("idCard", idCardInfo.getId());
                                                localIntent.putExtra("registrationId", registrationId);
                                                localIntent.putExtra("expressMoney", expressMoney);
                                                ScanCardActivity.this.startActivity(localIntent);
                                                ScanCardActivity.this.finish();
                                            }
                                        });
                                    } else if (code == 505) {
                                        Intent intent = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                        intent.putExtra("errorInfo", msg);
                                        intent.putExtra("code", 4);
                                        intent.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                        ScanCardActivity.this.startActivity(intent);
                                        ScanCardActivity.this.finish();
                                    } else {
                                        Intent intent = new Intent(ScanCardActivity.this, ErrorActivity.class);
                                        intent.putExtra("code", 1);
                                        intent.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                                        intent.putExtra("errorInfo", msg);
                                        ScanCardActivity.this.startActivity(intent);
                                        ScanCardActivity.this.finish();
                                    }
                                }
                            } catch (Exception e) {
                                runOnUiThread(new Runnable() {
                                    public void run() {
                                        ToastUtil.show(ScanCardActivity.this, "程序异常");
                                        ScanCardActivity.this.startActivity(new Intent(ScanCardActivity.this, MainActivity.class));
                                        ScanCardActivity.this.finish();
                                    }
                                });
                            } finally {
                                OnBnStop();
                            }
                        }
                    }
                    countdownLatch.countDown();
                }
            }).start();
        } catch (IDCardReaderException ex) {
            writeLogToFile("读卡失败，错误信息：" + ex.getMessage());
            System.out.println("读卡失败，信息错误：" + ex.getMessage());
        }
    }

    public void OnBnStop() {
        if (!this.bopen) {
            return;
        }
        bStoped = true;
        mReadCount = 0;
        try {
            countdownLatch.await(2, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        try {
            idCardReader.close(0);
        } catch (IDCardReaderException e) {
            e.printStackTrace();
        }
        this.bopen = false;
    }

    public void finish() {
        super.finish();
        this.bStoped = true;
        BiometricFactory.destroy(this.idCardReader);
    }

    public Context getContext() {
        return this.getApplicationContext();
    }

    @Override
    protected void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        this.pageStatus = this.getIntent().getIntExtra("pageStatus", 1);
        this.setContentView(R.layout.activiy_scan_card);
        (this.soundPoolHelper = new SoundPoolHelper((Context) this)).setEnableSound(true);
        this.soundPoolHelper.playSound(FaceStatusEnum.Idcard_Identify);
        this.textView = this.findViewById(R.id.textView12);
        if (this.pageStatus == 2) {
            this.textView.setText("手动输入身份证");
            this.textView.setOnClickListener(new View.OnClickListener() {
                public void onClick(final View view) {
                    final Intent intent = new Intent((Context) ScanCardActivity.this, InputCardNumberActivity.class);
                    intent.putExtra("pageStatus", ScanCardActivity.this.pageStatus);
                    ScanCardActivity.this.startActivity(intent);
                    ScanCardActivity.this.finish();
                }
            });
        } else {
            this.textView.setVisibility(View.INVISIBLE);
        }
        this.mLoading = this.findViewById(R.id.loading);
        this.findViewById(R.id.back).setOnClickListener(new View.OnClickListener() {
            public void onClick(final View view) {
                final ScanCardActivity this$0 = ScanCardActivity.this;
                this$0.startActivity(new Intent((this$0), MainActivity.class));
                ScanCardActivity.this.finish();
            }
        });
        this.findViewById(R.id.backTV).setOnClickListener(new View.OnClickListener() {
            public void onClick(final View view) {
                final ScanCardActivity this$0 = ScanCardActivity.this;
                this$0.startActivity(new Intent((Context) this$0, MainActivity.class));
                ScanCardActivity.this.finish();
            }
        });
        this.mUsbPrinter = new UsbPrinter(this.getApplicationContext());
        LogHelper.setLevel(2);

        this.mContext = this.getApplicationContext();

        Map idrparams = new HashMap();
        idrparams.put(ParameterHelper.PARAM_KEY_VID, VID);
        idrparams.put(ParameterHelper.PARAM_KEY_PID, PID);
        this.idCardReader = IDCardReaderFactory.createIDCardReader(this, TransportType.USB, idrparams);

        this.startIDCardReader();
        new Thread(new Runnable() {
            @Override
            public void run() {
                System.out.println("开始识别身份证==========================================");
                ScanCardActivity.this.OnBnBegin();
            }
        }).start();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.bStoped = true;
        BiometricFactory.destroy(this.idCardReader);
    }

    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    public String print(final String name, final String number, final String waitCount) {
        final UsbDevice correctDevice = this.getCorrectDevice();
        if (correctDevice == null || !this.mUsbPrinter.open(correctDevice)) {
            return "null";
        }
        this.mUsbPrinter.init();
        final String format = String.format("%04XH", this.mUsbPrinter.getStatus2());
        if ("8018H".equals(format)) {
            this.mUsbPrinter.doFunction(7, 1, 0);
            this.mUsbPrinter.doFunction(1, 2, 1);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 15, 0);
            this.mUsbPrinter.outputStringLn("健康证办理");
            this.mUsbPrinter.newline();
            this.mUsbPrinter.resetFont();
            this.mUsbPrinter.doFunction(7, 1, 0);
            this.mUsbPrinter.doFunction(1, 1, 1);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 22, 0);
            final UsbPrinter mUsbPrinter = this.mUsbPrinter;
            final StringBuilder sb = new StringBuilder();
            sb.append("姓名：");
            sb.append(name);
            mUsbPrinter.outputStringLn(sb.toString());
            this.mUsbPrinter.doFunction(7, 1, 0);
            this.mUsbPrinter.newline();
            this.mUsbPrinter.doFunction(1, 1, 1);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 22, 0);
            final UsbPrinter mUsbPrinter2 = this.mUsbPrinter;
            final StringBuilder sb2 = new StringBuilder();
            sb2.append("编号：");
            sb2.append(number);
            mUsbPrinter2.outputStringLn(sb2.toString());
            this.mUsbPrinter.newline();
            this.mUsbPrinter.doFunction(1, 1, 1);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 22, 0);
            final UsbPrinter mUsbPrinter3 = this.mUsbPrinter;
            final StringBuilder sb3 = new StringBuilder();
            sb3.append("等待人数：");
            sb3.append(waitCount);
            mUsbPrinter3.outputStringLn(sb3.toString());
            this.mUsbPrinter.newline();
            this.mUsbPrinter.doFunction(1, 0, 0);
            this.mUsbPrinter.doFunction(11, 1, 0);
            this.mUsbPrinter.doFunction(13, 15, 0);
            final SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            final UsbPrinter mUsbPrinter4 = this.mUsbPrinter;
            final StringBuilder sb4 = new StringBuilder();
            sb4.append("当前时间：");
            sb4.append(simpleDateFormat.format(new Date()));
            mUsbPrinter4.outputStringLn(sb4.toString());
            this.mUsbPrinter.doFunction(12, 0, 0);
            this.mUsbPrinter.close();
            return format;
        }
        return format;
    }
}
